package ac.svn.accesscontrol.hooks.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JLabel;
import javax.swing.JToolBar;

import ac.svn.accesscontrol.ui.IUIConstants;
import ac.svn.accesscontrol.ui.UIComponentLibrary;

public class ConnectionServer 
{
	
	boolean exitCondition;
	private ServerSocket serverSocket;
	private Thread connectionThread ;
	private JLabel srvrStatusLabel;; 
	
	public ConnectionServer()
	{
		exitCondition = false;
		serverSocket =null;
		connectionThread = null;
		srvrStatusLabel = new JLabel("Validation server running..", JLabel.LEADING);
	}

	public boolean startServer()
	{
		JToolBar  toolBar = (JToolBar) UIComponentLibrary.getComponent(IUIConstants.C_STATUS_BAR);
		toolBar.add(srvrStatusLabel);
		toolBar.addSeparator();
		
		boolean serverInitStatus = false;
		try{
			serverSocket = new ServerSocket(64608);
			srvrStatusLabel.setText("Validation server started!");
			serverInitStatus =	startService();
		}catch(Exception e)
		{
			serverInitStatus = false;
			e.printStackTrace();
		}
		return serverInitStatus;
	}

	private boolean startService() {
		connectionThread = new Thread(new Runnable() {
			@Override
			public void run() {
				srvrStatusLabel.setText("Ready to accept connections!");
				acceptConnection();				
			}
		});

		//start thread!
		connectionThread.start();
		
		if(null != connectionThread){
			return true;
		}
		else{
			return false;
		}
	}

	private void acceptConnection()
	{
		while(false == exitCondition)
		{
			try 
			{
				Socket socket = serverSocket.accept();
				srvrStatusLabel.setText("Connection accepted from " + socket.getInetAddress().toString());
				//TODO Create handle.
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void stopService()
	{
		exitCondition = true;
		if(connectionThread.isAlive())
		{
			connectionThread.interrupt();
		}
		connectionThread = null;
	}
}

